package com.yakami.ocean.view.fragment;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.jakewharton.rxbinding.view.RxView;
import com.yakami.ocean.AppManager;
import com.yakami.ocean.R;
import com.yakami.ocean.ServerAPI;
import com.yakami.ocean.bean.UserLoginInfo;
import com.yakami.ocean.event.Event;
import com.yakami.ocean.event.RxBus;
import com.yakami.ocean.model.SharePreferenceManager;
import com.yakami.ocean.model.SharePreferenceManager.User;
import com.yakami.ocean.utils.Tools;
import com.yakami.ocean.view.fragment.base.BaseFragment;

import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author Yakami, Created on 2016/4/27
 */
public class LoginFragment extends BaseFragment {

    @Bind(R.id.btn_login) Button mBtnLogin;
    @Bind(R.id.user_name) EditText mUserName;
    @Bind(R.id.password) EditText mPassword;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceBundle) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        ButterKnife.bind(this, view);

        RxView.clicks(mBtnLogin)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> {
                    String userName = mUserName.getText().toString();
                    String password = mPassword.getText().toString();
                    if (!Tools.isEmpty(userName) && !Tools.isEmpty(password)) {
                        login(userName, password);
                    } else toast(mRes.getString(R.string.please_input_completely));
                });

        return view;
    }

    public void login(String name, String pwd) {
        ServerAPI.getOceanAPI()
                .login(name, pwd, true)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(userLoginInfo -> {
                    if (userLoginInfo.result.contains("登录成功"))
                        loginSuccessful(userLoginInfo);
                    else
                        toast(userLoginInfo.result);
                });
    }

    public void loginSuccessful(UserLoginInfo user) {
        AppManager.mUser = user;
        SharedPreferences.Editor editor = SharePreferenceManager.getUser().edit();
        editor.putString(User.KEY_USER_NAME, user.name);
        editor.putString(User.KEY_PORTRAIT_URL, user.portraitUrl);
        editor.putInt(User.KEY_USER_ID, user.id);
        editor.apply();
        RxBus.getInstance().send(Event.EventType.LOGIN_SUCCESS, null);
        if (getActivity() != null)
            getActivity().finish();
    }
}
